package com.huanxing.cloud.security.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huanxing.cloud.common.core.constant.CommonConstants;
import com.huanxing.cloud.common.core.entity.Result;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 权限不足异常处理
 *
 * @author lijx
 * @date 2022/5/16 21:59
 * @version 1.0
 */
@Slf4j
@Component
@AllArgsConstructor
public class HxAccessDeniedHandler implements AccessDeniedHandler {
  private final ObjectMapper objectMapper;

  @Override
  public void handle(
      HttpServletRequest request,
      HttpServletResponse response,
      AccessDeniedException accessDeniedException)
      throws IOException, ServletException {
    String msg = StrUtil.format("请求访问：{}，无权访问", request.getRequestURI());
    response.setCharacterEncoding(CommonConstants.UTF8);
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    Result<String> result = new Result<>();
    result.setCode(CommonConstants.FAIL);
    result.setMsg(msg);
    response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
    PrintWriter printWriter = response.getWriter();
    printWriter.append(objectMapper.writeValueAsString(result));
  }
}
